
// VectorAnalyserDlg.cpp : implementation file
//

#include "stdafx.h"
#include "VectorAnalyser.h"
#include "VectorAnalyserDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	enum { IDD = IDD_ABOUTBOX };

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support

// Implementation
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()


// CVectorAnalyserDlg dialog




CVectorAnalyserDlg::CVectorAnalyserDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CVectorAnalyserDlg::IDD, pParent)
	, m_strInfo(_T("Ready"))
	, m_nSimpleNumber(1000)
	, m_strPivot(_T(""))
	, m_strRawFileName(_T(""))
	, m_nMaxDistance(0)
	, m_nMatchedNumber(0)
	, m_nNormalSeedNumber(100)
	, m_nNormalSearchRange(400)
	, m_nMultipSeedNumber(20)
	, m_nMultipSearchStep(6)
	, m_nMinSearchRange(150)
	, m_nMaxSearchRange(900)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CVectorAnalyserDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Text(pDX, IDC_EDIT1, m_strInfo);
	DDX_Text(pDX, IDC_EDIT2, m_nSimpleNumber);
	DDV_MinMaxUInt(pDX, m_nSimpleNumber, 1, 23000);
	DDX_Text(pDX, IDC_EDIT3, m_strPivot);
	DDX_Text(pDX, IDC_EDIT4, m_nMaxDistance);
	DDX_Text(pDX, IDC_EDIT5, m_nMatchedNumber);
	DDX_Text(pDX, IDC_EDIT6, m_nNormalSeedNumber);
	DDX_Text(pDX, IDC_EDIT7, m_nNormalSearchRange);
	DDX_Text(pDX, IDC_EDIT9, m_nMultipSeedNumber);
	DDX_Text(pDX, IDC_EDIT12, m_nMultipSearchStep);
	DDX_Text(pDX, IDC_EDIT10, m_nMinSearchRange);
	DDX_Text(pDX, IDC_EDIT11, m_nMaxSearchRange);
}

BEGIN_MESSAGE_MAP(CVectorAnalyserDlg, CDialog)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	//}}AFX_MSG_MAP
	ON_BN_CLICKED(IDC_BUTTON_IMPORT_DATA, &CVectorAnalyserDlg::OnBnClickedButtonImportData)
	ON_BN_CLICKED(IDC_BUTTON_Get_DISTRIBUTION, &CVectorAnalyserDlg::OnBnClickedButtonGetDistribution)
	ON_BN_CLICKED(IDC_BUTTON_Get_RESULT, &CVectorAnalyserDlg::OnBnClickedButtonGetResult)
	ON_BN_CLICKED(IDC_BUTTON_GENERATE_SEED_FILE, &CVectorAnalyserDlg::OnBnClickedButtonGenerateSeedFile)
END_MESSAGE_MAP()


// CVectorAnalyserDlg message handlers

BOOL CVectorAnalyserDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		BOOL bNameValid;
		CString strAboutMenu;
		bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
		ASSERT(bNameValid);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon

	// TODO: Add extra initialization here

//CVectorKey k1("0.548076	0.184312	0.197667	0.235905	-1.287708	-0.963008	-1.124946	-1.209885	1.547753	0.74033	0.912665	1.033537	1.523431	0.92097	1.001591	1.071083"),k2("-0.057011	-0.229294	-0.194915	-0.193313	-1.066157	0.208741	-0.273153	-0.300812	1.167628	0.330242	0.588238	0.603702	0.517578	-0.08329	0.06008	0.070788");
//	int nRes = CVectorKey::GetDistance(k1,k2);
//	return nRes;
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CVectorAnalyserDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CVectorAnalyserDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this function to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CVectorAnalyserDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}


void CVectorAnalyserDlg::OnBnClickedButtonImportData()
{
	// TODO: Add your control notification handler code here
	CFileDialog cFile(TRUE,"asc",NULL,6,"Vectro Data Files (*.asc)|*.asc||");
	if(cFile.DoModal()==IDOK)
	{
		ifstream fin(cFile.GetPathName().GetString());
		if(fin)
		{
			this->SetWindowTextA(cFile.GetFileName().GetString());
			m_strRawFileName = cFile.GetFileName().Left(cFile.GetFileName().ReverseFind('.'));
			m_strFilePos = cFile.GetPathName().Left(cFile.GetPathName().Find(cFile.GetFileName()));
			m_cKeyVector.clear();
			char Buffer[1024];
			while(fin.getline(Buffer,1024))
			{
				CVectorKey tmp;
				if(tmp.FromString(Buffer))
				{
					m_cKeyVector.push_back(tmp);
				}
			}
			m_strInfo.Format("Data Size: %u.",m_cKeyVector.size());
			this->UpdateData(FALSE);
			this->MessageBox("Success");
			GetDlgItem(IDC_BUTTON_Get_DISTRIBUTION)->EnableWindow();
			GetDlgItem(IDC_BUTTON_Get_RESULT)->EnableWindow();
			GetDlgItem(IDC_BUTTON_IMPORT_DATA)->EnableWindow(FALSE);
			GetDlgItem(IDC_BUTTON_GENERATE_SEED_FILE)->EnableWindow();
			return ;
		}
		else
		{
			this->MessageBox("Open file error.");
		}
	}
}

void CVectorAnalyserDlg::OnBnClickedButtonGetDistribution()
{
	// TODO: Add your control notification handler code here
	this->UpdateData();
	vector<unsigned int> cSel;
	GetRandomSequence(0,this->m_cKeyVector.size(),this->m_nSimpleNumber,cSel);
	CCalculator cCal;
	double dMaxDis = 0;
	for(DWORD i = 0;i<m_nSimpleNumber;i++)
	{
		for(DWORD j = i+1;j<m_nSimpleNumber;j++)
		{
			double dDis = CVectorKey::GetDistance(m_cKeyVector[cSel[i]],m_cKeyVector[cSel[j]]);
			cCal.Add(dDis);
			dMaxDis = max(dMaxDis,dDis);
		}
	}
	cCal.Calculate();
	vector<pair<double ,double>> cPdf,cCdf;
	cCal.GetPDF(100,0,dMaxDis,cPdf);
	cCal.GetCDF(100,0,dMaxDis,cCdf);
	CString strName("VectorDataDistribution_of_");
	strName.Append(m_strRawFileName);
	CFileDialog cFile(FALSE,"eps",strName,6,"EPS Files (*.eps)|*.eps||");
	if(cFile.DoModal()==IDOK)
	{
		CString strFigureNamePath(cFile.GetPathName());
		CString strRawDataNamePath(strFigureNamePath);
		strRawDataNamePath=strRawDataNamePath.Left(strRawDataNamePath.ReverseFind('.'));
		strRawDataNamePath.Append(".dat");
		CString strScriptNamePath(strFigureNamePath.Left(strFigureNamePath.ReverseFind('.')));
		strScriptNamePath.Append(".plt");
		ofstream fout(strRawDataNamePath.GetString());
		if(fout)
		{
			for (unsigned i = 0;i<cPdf.size();i++)
			{
				fout<<cPdf[i].first<<" "<<cPdf[i].second<<" "<<cCdf[i].first<<" "<<cCdf[i].second<<endl;	
			}
			fout.close();
		}
		else
		{
			this->MessageBox("Create Data File Error!");
			return ;
		}
		CString strXCoordinate;
		strXCoordinate.Format("0,%u,%u,%u,%u,%u",(int)(dMaxDis/5*1),(int)(dMaxDis/5*2),(int)(dMaxDis/5*3),(int)(dMaxDis/5*4),(int)dMaxDis );
		CString script("reset \n");
		script.AppendFormat("set term postscript eps color enhanced \n");
		script.AppendFormat("set output '%s'\n",strFigureNamePath.GetString());
		script.AppendFormat("unset key \n");
		script.AppendFormat("set multiplot\n");
		script.AppendFormat("set size 0.4,0.6\n");
		script.AppendFormat("set origin 0.1,0.1\n");
		script.AppendFormat("set title '(a) PDF'\n");
		script.AppendFormat("set xlabel 'Distance'\n");
		script.AppendFormat("set xtics (%s) \n",strXCoordinate.GetString());
		script.AppendFormat("plot '%s' using 1:2   with l lt 1 lw 2 \n",strRawDataNamePath.GetString());
		
		script.AppendFormat("set size 0.4,0.6\n");
		script.AppendFormat("set origin 0.5,0.1\n");
		script.AppendFormat("set title '(b) CDF'\n");
		script.AppendFormat("set xlabel 'Distance'\n");
		script.AppendFormat("set xtics (%s) \n",strXCoordinate.GetString());
		script.AppendFormat("plot '%s' using 3:4   with l lt 1 lw 2 \n",strRawDataNamePath.GetString());
		script.AppendFormat("unset multiplot\n");
		script.AppendFormat("reset \n");
		script.AppendFormat("set term windows\n");
		script.AppendFormat("unset key \n");
		script.AppendFormat("set multiplot\n");
		script.AppendFormat("set size 0.4,0.6\n");
		script.AppendFormat("set origin 0.1,0.1\n");
		script.AppendFormat("set title '(a) PDF'\n");
		script.AppendFormat("set xlabel 'Distance'\n");
		script.AppendFormat("set xtics (%s) \n",strXCoordinate.GetString());
		script.AppendFormat("plot '%s' using 1:2   with l lt 1 lw 2 \n",strRawDataNamePath.GetString());
		
		script.AppendFormat("set size 0.4,0.6\n");
		script.AppendFormat("set origin 0.45,0.1\n");
		script.AppendFormat("set title '(b) CDF'\n");
		script.AppendFormat("set xlabel 'Distance'\n");
		script.AppendFormat("set xtics (%s) \n",strXCoordinate.GetString());
		script.AppendFormat("plot '%s' using 3:4   with l lt 1 lw 2 \n",strRawDataNamePath.GetString());
		script.AppendFormat("unset multiplot\n");
		FILE *pFile ;
		if(0==fopen_s(&pFile,strScriptNamePath.GetString(),"w"))
		{
			fwrite(script.GetBuffer(),1,script.GetLength(),pFile);
			fclose(pFile);
			CString cmd;
			cmd.Format("pgnuplot.exe -persist \"%s\"",strScriptNamePath.GetString());
			WinExec(cmd.GetString(),SW_SHOW);
		}
		else
		{
			MessageBox("Open File Error!");
			return ;
		}
	}
}


void CVectorAnalyserDlg::OnBnClickedButtonGetResult()
{
	// TODO: Add your control notification handler code here
	this->UpdateData();
	CVectorKey tmp;
	if(tmp.FromString(this->m_strPivot.GetString()))
	{
		this->m_nMatchedNumber = 0;
		for(unsigned i = 0;i<this->m_cKeyVector.size();i++)
		{
			if(CVectorKey::GetDistance(tmp,m_cKeyVector[i])<=m_nMaxDistance)
			{
				m_nMatchedNumber++;
			}
		}
		m_strPivot.Replace('\n',' ');
		m_strPivot.Replace('\t',' ');
	}
	else
	{
		this->m_nMatchedNumber = 0;
		this->m_strPivot.Empty();
		this->MessageBox("Pivot ERROR!");
	}
	this->UpdateData(FALSE);
}

void CVectorAnalyserDlg::OnBnClickedButtonGenerateSeedFile()
{
	// TODO: Add your control notification handler code here
	this->UpdateData();
	CString strNormalSeedPath(m_strFilePos);
	CString strRangeSeedPath(m_strFilePos);
	strNormalSeedPath.Append("Normal_Seed.seed");
	strRangeSeedPath.Append("Range_Seed.seed");
	if(this->m_nMultipSeedNumber>this->m_cKeyVector.size()||this->m_nNormalSeedNumber>this->m_cKeyVector.size())
	{
		this->MessageBox("Not Enough Data");
		return;
	}
	ofstream fout(strNormalSeedPath.GetString());
	ofstream fout2(strRangeSeedPath.GetString());
	if(fout&&fout2)
	{
		vector<unsigned int> cSel;
		GetRandomSequence(0,this->m_cKeyVector.size()-1,m_nNormalSeedNumber,cSel);
		for(unsigned i = 0;i<cSel.size();i++)
		{
			CVectorKey &key = m_cKeyVector[cSel[i]];
			unsigned nRes = 0;
			for(unsigned j =0 ;j<m_cKeyVector.size();j++)
			{
				if(CVectorKey::GetDistance(key,m_cKeyVector[j])<=(int)this->m_nNormalSearchRange)
				{
					nRes++;
				}
			}
			fout<<key.ToString().c_str()<<endl<<nRes<<endl;
		}
		GetRandomSequence(0,this->m_cKeyVector.size()-1,m_nMultipSeedNumber,cSel);
		for(unsigned i = 0;i<cSel.size();i++)
		{
			CVectorKey &key = m_cKeyVector[cSel[i]];
			fout2<<key.ToString().c_str()<<endl;
			for(unsigned nStep = 0;nStep<this->m_nMultipSearchStep;nStep++)
			{
				unsigned nCurRange = this->m_nMinSearchRange+D2I((float)nStep*(m_nMaxSearchRange-m_nMinSearchRange)/(m_nMultipSearchStep-1));
				unsigned nRes = 0;
				for(unsigned j =0 ;j<m_cKeyVector.size();j++)
				{
					if(CVectorKey::GetDistance(key,m_cKeyVector[j])<=(int)nCurRange)
					{
						nRes++;
					}
				}
				fout2<<nRes<<endl;
			}
		}
		this->MessageBox("Success");
	}
	else
	{
		this->MessageBox("Create File Error");
	}
}
